/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * GUIP2PlanDeMovilizacionInternamiento.java
 *
 * Created on Oct 20, 2011, 2:44:34 AM
 */
package GUI.Procesamiento;

import BE.BELineaCardex;
import BE.BEMovimiento;
import BE.BEPallet;
import java.util.ArrayList;
import java.util.List;
import BL.BLGrafoAlmacen;
import BL.BLGRASP;
import BE.BENodo;
import BE.BEPosicionxRack;
import BL.BLCardex;
import BL.BLLineaMovimiento;
import BL.BLPosicionxrack;
import BL.BLmovimiento;
import BL.BLAlmacen;
import javax.swing.JOptionPane;
import GUI.Visualizacion.Ventana;
import GUI.Visualizacion.GestorDibujo;
import java.sql.Timestamp;
import org.apache.poi.hssf.record.formula.functions.Now;
import GUIalmacen.VentanaPrincipal;

/**
 *
 * @author fenartcos
 */
public class GUIP2PlanDeMovilizacionInternamiento extends javax.swing.JDialog {
    
    BLGrafoAlmacen blGrafoAlmacen;
    ArrayList<Integer> obligatorios;
    BLGRASP blGRASP;
    List<BEPallet> lstPallets;
    int rutaActual;
    List<BENodo> rutaSolucion;
    BEMovimiento objMovimiento;
    BEPosicionxRack objPosAux;
    BLCardex objGestotCardex;
    BLLineaMovimiento objLineaMantenimiento;
    BLAlmacen blAlmacen;
    List<BENodo> lstPosicionInternamiento;
    
    /** Creates new form GUIP2PlanDeMovilizacionInternamiento */
    public GUIP2PlanDeMovilizacionInternamiento(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }
    
    public GUIP2PlanDeMovilizacionInternamiento(java.awt.Frame parent, boolean modal, List<BEPallet> lstPallets, BEMovimiento mov, BEPosicionxRack posAux) {
        super(parent, modal);
        initComponents();
        this.lstPallets=lstPallets;
        
        objMovimiento= mov;
        objPosAux= posAux;
        
           
        blAlmacen = new BLAlmacen();
        blGrafoAlmacen = new BLGrafoAlmacen(blAlmacen.getAncho(),blAlmacen.getLargo());
        objGestotCardex= new BLCardex();
        blGrafoAlmacen.cargarRacks();
        obligatorios = blGrafoAlmacen.calcularObligatorios(lstPallets);
        
//        List<BENodo> grafo = blGrafoAlmacen.getBeGrafoAlmacen().getGrafo();
//        blGRASP = new BLGRASP (grafo.size(),obligatorios.size(),obligatorios,grafo);
//        
        this.lstPosicionInternamiento = blGrafoAlmacen.getNodosDespachoImpresionDePallet(lstPallets);
        
        //rutaSolucion = blGRASP.run(0.3, 100);        
        rutaSolucion = blGrafoAlmacen.generarRutaAlmacen(blGrafoAlmacen.getNodoInternamiento(lstPallets));
        
//        List<BENodo> rutaAux = new ArrayList<BENodo>();
//        for (int i=0; i<nodosDespacho.size(); i++){
//            int x=nodosDespacho.get(i).getX();
//            int y=nodosDespacho.get(i).getY();
//            //rutaSolucion.add(new BENodo(blGrafoAlmacen.getIdNodoXY(x,y),x,y));
//            rutaAux.add(blGrafoAlmacen.getBeGrafoAlmacen().getGrafo().get(blGrafoAlmacen.buscarNodoRutaRack(x, y)-1));
//        }
        
        String text = blGrafoAlmacen.imprimeRuta(rutaSolucion, obligatorios,"");
        rutaActual=rutaSolucion.size()-1;
        text="Distancia: "+rutaActual+"\n"+text;
        txtAreaSolucion.setText(text);
        txtAreaSolucion.setEditable(false);
    }
    


//    private void formWindowOpened(java.awt.event.WindowEvent evt) {                                  
//        
//        blGrafoAlmacen = new BLGrafoAlmacen(20,20);
//        blGrafoAlmacen.cargarRacks();
//        obligatorios = blGrafoAlmacen.calcularObligatorios(lstPallets);
//        List<BENodo> grafo = blGrafoAlmacen.getBeGrafoAlmacen().getGrafo();
//        blGRASP = new BLGRASP (grafo.size(),obligatorios.size(),obligatorios,grafo);
//        
//        List<BENodo> ruta = blGRASP.run(0.3, 1000);
//        String text = blGrafoAlmacen.imprimeRuta(ruta, obligatorios);
//        txtAreaSolucion.setText(text);
//        System.out.println(text);
//        txtAreaSolucion.setEditable(false);
//}       
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlGeneracion = new javax.swing.JPanel();
        lblGenerar = new javax.swing.JLabel();
        pbrGeneracion = new javax.swing.JProgressBar();
        btnVisualizar = new javax.swing.JButton();
        btnAceptar1 = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        txtAreaSolucion = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Plan de Movilización - Paso 2");

        pnlGeneracion.setBorder(javax.swing.BorderFactory.createTitledBorder("Generación"));

        lblGenerar.setText("Generando plan de movilización...");

        btnVisualizar.setText("Visualizar");
        btnVisualizar.setMaximumSize(new java.awt.Dimension(100, 25));
        btnVisualizar.setMinimumSize(new java.awt.Dimension(100, 25));
        btnVisualizar.setPreferredSize(new java.awt.Dimension(100, 25));
        btnVisualizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnVisualizarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout pnlGeneracionLayout = new javax.swing.GroupLayout(pnlGeneracion);
        pnlGeneracion.setLayout(pnlGeneracionLayout);
        pnlGeneracionLayout.setHorizontalGroup(
            pnlGeneracionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlGeneracionLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlGeneracionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblGenerar)
                    .addComponent(pbrGeneracion, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 475, Short.MAX_VALUE)
                    .addComponent(btnVisualizar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        pnlGeneracionLayout.setVerticalGroup(
            pnlGeneracionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlGeneracionLayout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addComponent(lblGenerar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pbrGeneracion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnVisualizar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        btnAceptar1.setText("Guardar");
        btnAceptar1.setMaximumSize(new java.awt.Dimension(100, 25));
        btnAceptar1.setMinimumSize(new java.awt.Dimension(100, 25));
        btnAceptar1.setPreferredSize(new java.awt.Dimension(100, 25));
        btnAceptar1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAceptar1ActionPerformed(evt);
            }
        });

        btnCancelar.setText("Cancelar");
        btnCancelar.setMaximumSize(new java.awt.Dimension(100, 25));
        btnCancelar.setMinimumSize(new java.awt.Dimension(100, 25));
        btnCancelar.setPreferredSize(new java.awt.Dimension(100, 25));
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        txtAreaSolucion.setColumns(20);
        txtAreaSolucion.setRows(5);
        jScrollPane2.setViewportView(txtAreaSolucion);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 507, Short.MAX_VALUE)
                    .addComponent(pnlGeneracion, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnAceptar1, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(pnlGeneracion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnAceptar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(17, 17, 17))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnAceptar1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAceptar1ActionPerformed
            
        // almaceno el movimiento
        
        int result=JOptionPane.showConfirmDialog(null,"Desea guardar los datos de internamiento del pallet??", "Registro del Intrernamiento",    JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        
        
         if (result==JOptionPane.YES_OPTION)
        {
        
            
            BLmovimiento blmov = new BLmovimiento();
            objMovimiento.setDestino(objPosAux);

            blmov.agregarInternamiento(objMovimiento);

            //almaceno la poscicion del Rack

            BLPosicionxrack objGestorPosRack = new BLPosicionxrack();
            objGestorPosRack.actualizarPosicion(objPosAux);

            BELineaCardex auxLineaCardex = new BELineaCardex();

            auxLineaCardex.setIdProducto(lstPallets.get(0).getProducto().getIdProducto());

            java.util.Date today = new java.util.Date();
            Timestamp fecha = new Timestamp(today.getTime());

            objGestotCardex.cargarCardexProducto(lstPallets.get(0).getProducto().getIdProducto());
            auxLineaCardex.setFecha(fecha);
            auxLineaCardex.setCantIngreso(lstPallets.get(0).getCantidad());
            auxLineaCardex.setCantSalida(0);
            auxLineaCardex.setDetalle("INGRESO");
            auxLineaCardex.set0rigen(0);
            auxLineaCardex.setDestino(objPosAux.getIdposicionxrack());

            auxLineaCardex.setTotalAlmacen(objGestotCardex.obtenerExistencias()+lstPallets.get(0).getCantidad());

            //objGestotCardex.guardarInternamiento(auxLineaCardex);

            this.dispose();
            
            
        }
        
        
            
    }//GEN-LAST:event_btnAceptar1ActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void btnVisualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVisualizarActionPerformed
        // TODO add your handling code here:
        try{
//        Ventana frmVentana = new Ventana();
//        this.setVisible(false);
//        GestorDibujo gestorDibujo = new GestorDibujo(frmVentana,rutaSolucion);
//        gestorDibujo.actualizaBackBuffer();
            VentanaPrincipal ventana = new VentanaPrincipal(rutaSolucion, lstPosicionInternamiento);
            ventana.setSize(ventana.getVx(),ventana.getVy());
            ventana.setVisible(true);
            ventana.setResizable(false);
        }
        catch (Exception e){
            
        }
    }//GEN-LAST:event_btnVisualizarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(GUIP2PlanDeMovilizacionInternamiento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(GUIP2PlanDeMovilizacionInternamiento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(GUIP2PlanDeMovilizacionInternamiento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(GUIP2PlanDeMovilizacionInternamiento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                GUIP2PlanDeMovilizacionInternamiento dialog = new GUIP2PlanDeMovilizacionInternamiento(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAceptar1;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnVisualizar;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lblGenerar;
    private javax.swing.JProgressBar pbrGeneracion;
    private javax.swing.JPanel pnlGeneracion;
    private javax.swing.JTextArea txtAreaSolucion;
    // End of variables declaration//GEN-END:variables
}
